package com.xyc.www.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.xyc.common.constant.AuthServerConstant;
import com.xyc.common.exception.BizCodeEnume;
import com.xyc.common.utils.R;
import com.xyc.common.vo.MemberResponseVo;
import com.xyc.www.gulimall.auth.feign.MemberFeignService;
import com.xyc.www.gulimall.auth.feign.ThreadPartFeignService;
import com.xyc.www.gulimall.auth.vo.UserLoginVo;
import com.xyc.www.gulimall.auth.vo.UserRegisterVo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThreadPartFeignService threadPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {

        //TODO 1、接口防刷。

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //2、验证码的再次校验。redis
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();

        //redis缓存验证码，防止同一个手机号在60秒内再次发送验证码
        stringRedisTemplate.opsForValue().set(
                AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,
                code,
                10,
                TimeUnit.MINUTES
        );

        threadPartFeignService.sendCode(phone, code.split("_")[0]);
        return R.ok();
    }

    /**
     * TODO 重定向携带数据，利用Session原理。将数据放在session中。
     * TODO 只要跳到下一个页面取出数据以后，session里面得数据就会删掉
     * <p>
     * TODO 1、分布式下的session问题
     * <p>
     * RedirectAttributes redirectAttributes 模拟重定向携带数据
     *
     * @param registerVo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo,
                           BindingResult result,
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors()
                    .stream()
                    .collect(Collectors
                            .toMap(
                                    FieldError::getField,
                                    FieldError::getDefaultMessage
                            )
                    );
//            model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页-->forward:/reg.html 转发会将当前请求方式post转为请求方式get(路径映射默认get)
            //直接路径映射reg会重新提交表单
            //所以使用重定向：但是重定向不会携带当前数据，可以通过redirectAttributes将数据带上
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //1、校验验证码
        String code = registerVo.getCode();

        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码；令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                //验证码通过
                // 真正注册，调用远程服务
                R r = memberFeignService.register(registerVo);
                if (r.getCode() == 0) {
                    //成功

                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.get("msg").toString());
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        if (session.getAttribute(AuthServerConstant.LOGIN_USER) == null) {
            //设置登录
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo,
                        RedirectAttributes redirectAttributes,
                        HttpSession session
    ) {//此处的表单提交的数据，不是json格式，而是kv格式

        //远程登录
        R r = memberFeignService.login(userLoginVo);
        System.out.println(r);
        if (r.getCode() == 0) {//0成功
            MemberResponseVo data = JSON.parseObject(JSON.toJSONString(r.get("data")), MemberResponseVo.class);
            //将数据放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) r.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
